const fs = require("fs")
const path = require("path")
const request = require("request")
const writeJsonFile = (filePath, jsonData) => {
    try {
        const jsonStr = JSON.stringify(jsonData)
        fs.writeFileSync(filePath, jsonStr)
    } catch (error) {
        console.error(`写入文件出错：${JSON.stringify(error)}`)
    }
}
const readJsonFile = (filePath, errorReturn = [], encoding = 'utf-8') => {
    try {
        const data = fs.readFileSync(filePath, encoding)
        const jsonData = JSON.parse(data)
        return jsonData
    } catch (error) {
        return errorReturn
    }
}
//检测文件或者文件夹存在 nodeJS
const fsExistsSync = (path) => {
    try {
        fs.accessSync(path, fs.F_OK);
    } catch (e) {
        return false;
    }
    return true;
}
const downloadFileByUrl = (url, saveDirPath, saveFileName) => {
    let filename = url.substring(url.lastIndexOf('/') + 1)
    filename = filename ? filename : new Date().getTime()
    const stream = fs.createWriteStream(path.join(saveDirPath, saveFileName || filename))
    request(url).pipe(stream).on('close', (err) => {
    })
}
module.exports = {
    writeJsonFile,
    readJsonFile,
    downloadFileByUrl,
    fsExistsSync
}